//
//  SecondViewController.m
//  lovergotest
//
//  Created by liudonghuan on 14-8-12.
//  Copyright (c) 2014年 liudonghuan. All rights reserved.
//

#import "LGUtil.h"
#import "DataCenter.h"
#import "ShouCangViewController.h"
#import "SCShaiXuanTableViewCell.h"

@interface ShouCangViewController ()

@end
typedef enum{
    mainT = 0,
    step1T,
    step2T,
    step3T,
}whichTable;
@implementation ShouCangViewController

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

-(void)loadView
{   _pageNum = 1;
    _locManager = [[CLLocationManager alloc]init];
    _locManager.delegate = self;
    _locManager.desiredAccuracy = kCLLocationAccuracyBest;
    _locManager.distanceFilter = 100;
    [_locManager startUpdatingLocation];

    _totalData = [[NSMutableArray alloc]init];
    _scView = [[ShouCangView alloc] initWithFrame:[LGUtil getViewFrame]];
    _shaixuan = [[SCShaiXuan alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 200)];
    _shaixuan.sxDelegate = self;
    _scView.scTabV.delegate = self;
    _scView.scTabV.dataSource = self;
    _shaixuan.step1TB.delegate = self;
    _shaixuan.step1TB.dataSource = self;
    _shaixuan.step2TB.delegate = self;
    _shaixuan.step2TB.dataSource = self;
    _shaixuan.step3TB.delegate = self;
    _shaixuan.step3TB.dataSource = self;
    _lonLabel = [NSString stringWithFormat:@"%@",@""];
    _latLabel = [NSString stringWithFormat:@"%@",@""];
    _scView.scTabV.tag = mainT;
    _shaixuan.step1TB.tag = step1T;
    _shaixuan.step2TB.tag = step2T;
    _shaixuan.step3TB.tag = step3T;
    _s1data = @"cat001";
    _s2data = @"";
    _s3data = @"listOrder";
    UIButton* rBtn = [[UIButton alloc] initWithFrame:CGRectMake(0,0,30,30)];

    [rBtn setImage:[UIImage imageNamed:@"bg_select_normal.png"]forState:UIControlStateNormal];
    [rBtn addTarget:self action:@selector(shareBtnclick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* rightItem = [[UIBarButtonItem alloc] initWithCustomView:rBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
    [self stepArrayData];//初始化数据
    [self setupRefresh];
    [self setView:_scView];
    [self.view addSubview:_shaixuan];
    _shaixuan.hidden = YES;
    //关于获取当前经纬度
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"barBG_blue.png"] forBarMetrics:UIBarMetricsDefault];
    [super viewWillAppear:animated];
    [MobClick beginLogPageView:@"收藏"];
}
-(void)resetShaiXuan
{
    _s1data = @"cat001";
    _s2data = @"";
    _s3data = @"listOrder";
    [_shaixuan.step1 setTitle:@"餐饮" forState:UIControlStateNormal];
    [_shaixuan.step2 setTitle:@"全部" forState:UIControlStateNormal];
    [_shaixuan.step3 setTitle:@"默认排序" forState:UIControlStateNormal];
    
}
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
    //结构体，存储位置坐标
    CLLocationCoordinate2D loc = [newLocation coordinate];
    float longitude = loc.longitude;
    float latitude = loc.latitude;
    _lonLabel = [NSString stringWithFormat:@"%f",longitude];
    _latLabel = [NSString stringWithFormat:@"%f",latitude];
    
}
-(void)stepBtnOnclick:(UIButton *)btn
{
    _shaixuan.frame = CGRectMake(0, 0, SCREEN_WIDTH, 200);
    switch (btn.tag) {
        case step1:
            if (_shaixuan.step1TB.hidden == NO) {
                _shaixuan.step1TB.hidden =YES;
                [_shaixuan.step1 setBackgroundImage:[UIImage imageNamed:@"shaixuan_up"] forState:UIControlStateNormal];
            }else{
                [_shaixuan.step1TB reloadData];
                _shaixuan.step1TB.hidden = NO;
                _shaixuan.step2TB.hidden = YES;
                _shaixuan.step3TB.hidden = YES;
                [_shaixuan.step1 setBackgroundImage:[UIImage imageNamed:@"shaixuan_down"] forState:UIControlStateNormal];
                [_shaixuan.step2 setBackgroundImage:[UIImage imageNamed:@"shaixuan_up"] forState:UIControlStateNormal];
                [_shaixuan.step3 setBackgroundImage:[UIImage imageNamed:@"shaixuan_up"] forState:UIControlStateNormal];
            }
            break;
        case step2:
            if (_shaixuan.step2TB.hidden == NO) {
                _shaixuan.step2TB.hidden =YES;
                [_shaixuan.step2 setBackgroundImage:[UIImage imageNamed:@"shaixuan_up"] forState:UIControlStateNormal];
            }else{
                [_shaixuan.step2TB reloadData];
                _shaixuan.step1TB.hidden = YES;
                _shaixuan.step2TB.hidden = NO;
                _shaixuan.step3TB.hidden = YES;
                [_shaixuan.step2 setBackgroundImage:[UIImage imageNamed:@"shaixuan_down"] forState:UIControlStateNormal];
                [_shaixuan.step1 setBackgroundImage:[UIImage imageNamed:@"shaixuan_up"] forState:UIControlStateNormal];
                [_shaixuan.step3 setBackgroundImage:[UIImage imageNamed:@"shaixuan_up"] forState:UIControlStateNormal];
            }
            break;
        case step3:
            if (_shaixuan.step3TB.hidden == NO) {
                _shaixuan.step3TB.hidden =YES;
                [_shaixuan.step3 setBackgroundImage:[UIImage imageNamed:@"shaixuan_up"] forState:UIControlStateNormal];
            }else{
                [_shaixuan.step3TB reloadData];
                _shaixuan.step1TB.hidden = YES;
                _shaixuan.step2TB.hidden = YES;
                _shaixuan.step3TB.hidden = NO;
                [_shaixuan.step3 setBackgroundImage:[UIImage imageNamed:@"shaixuan_down"] forState:UIControlStateNormal];
                [_shaixuan.step1 setBackgroundImage:[UIImage imageNamed:@"shaixuan_up"] forState:UIControlStateNormal];
                [_shaixuan.step2 setBackgroundImage:[UIImage imageNamed:@"shaixuan_up"] forState:UIControlStateNormal];
            }
            break;
        default:
            break;
    }
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView//一旦用户触碰到主scrollV，马上隐藏其他的tableV
{
    if (scrollView.tag == mainT) {
        [_shaixuan hiddenAllTB];
    }
}
-(void)viewDidAppear:(BOOL)animated
{
    [_scView.scTabV headerBeginRefreshing];
    _shaixuan.hidden = YES;
    _scView.scTabV.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-BOTTOMBAR-STATUSBAR);
}
-(void)viewDidUnload
{
    [_scView.scTabV headerEndRefreshing];
    [_scView.scTabV footerEndRefreshing];
}
-(void)shareBtnclick:(id)sender//点击弹出或隐藏排序视图排序视图
{
    if (_shaixuan.hidden == YES) {
        _scView.scTabV.frame = CGRectMake(0, 37, SCREEN_WIDTH, SCREEN_HEIGHT-BOTTOMBAR-STATUSBAR-37);
        _scView.topline.hidden = YES;
        _shaixuan.hidden = NO;
    }else{
        _scView.scTabV.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-BOTTOMBAR-STATUSBAR);
        _shaixuan.hidden = YES;
        _scView.topline.hidden = NO;
    }
}

#pragma mark - Table view data source and delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView.tag == mainT) {//收藏列表
        return _totalData.count;
    }else if(tableView.tag == step1T){//筛选第一个列表
        return _sort.count;
    }else if (tableView.tag == step2T){//筛选第二个列表
        if ([_s1data isEqualToString:@"cat001"]) {//第一个选中的是餐饮
            return _canyin.count;
        }else{//第一个选中的是娱乐
            return _yule.count;
        }
    }else if (tableView.tag == step3T){
        return _fangshi.count;
    }else{
        return 2;
    }
    
    
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == mainT) {
        ShouCangViewCell *cell = [[ShouCangViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                                         reuseIdentifier:nil];
        NSMutableDictionary*  dict = _totalData[indexPath.row];
        NSString *mainimage = [NSString stringWithFormat:@"%@%@%@",imagebaseUrl,shangJiaImgSPath,[dict objectForKey:@"icoImageUrl"]];
        cell.scHeadImg.imageUrl = mainimage;
        [cell.scHeadImg.layer setMasksToBounds:YES];
        [cell.scHeadImg.layer setCornerRadius:2];
        cell.scTitleLab.text = [dict objectForKey:@"placeName"];
        cell.scPriceLab.text = [NSString stringWithFormat:@"%@%@",@"人均：",[dict objectForKey:@"payRank"]];
        cell.scAddressLab.text = [dict objectForKey:@"detailAdress"];
        return cell;
    }else if(tableView.tag == step1T){//筛选第一个列表
        NSString * scViewCell = [NSString stringWithFormat:@"%@%ld",@"SCShaiXuanViewCell1",(long)[indexPath row]];
        SCShaiXuanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:scViewCell];
        if (cell) {
            return cell;
        }else{
            SCShaiXuanTableViewCell *cell = [[SCShaiXuanTableViewCell alloc]initByTitle:[_sort objectAtIndex:indexPath.row]];
            return cell;
        }
        
    }else if (tableView.tag == step2T){//筛选第二个列表
        if ([_s1data isEqualToString:@"cat001"]) {//第一个选中的是餐饮
            NSString * scViewCell = [NSString stringWithFormat:@"%@%ld",@"SCShaiXuanViewCell2",(long)[indexPath row]];
            SCShaiXuanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:scViewCell];
            if (cell) {
                return cell;
            }else{
                SCShaiXuanTableViewCell *cell = [[SCShaiXuanTableViewCell alloc]initByTitle:[_canyin objectAtIndex:indexPath.row]];
                return cell;
            }
        }else{//第一个选中的是娱乐
            NSString * scViewCell = [NSString stringWithFormat:@"%@%ld",@"SCShaiXuanViewCell3",(long)[indexPath row]];
            SCShaiXuanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:scViewCell];
            if (cell) {
                return cell;
            }else{
                SCShaiXuanTableViewCell *cell = [[SCShaiXuanTableViewCell alloc]initByTitle:[_yule objectAtIndex:indexPath.row]];
                return cell;
            }
        }
    }else if (tableView.tag == step3T){
        NSString * scViewCell = [NSString stringWithFormat:@"%@%ld",@"SCShaiXuanViewCell4",(long)[indexPath row]];
        SCShaiXuanTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:scViewCell];
        if (cell) {
            return cell;
        }else{
            SCShaiXuanTableViewCell *cell = [[SCShaiXuanTableViewCell alloc]initByTitle:[_fangshi objectAtIndex:indexPath.row]];
            return cell;
        }
    }else{
        return NULL;
    }
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == mainT) {//收藏列表
        NSMutableDictionary*  dictleft = _totalData[indexPath.row];
        NSString *para = [dictleft objectForKey:@"uuid"];
        ShangJiaViewController *_shangJiaViewController = [[ShangJiaViewController alloc]initWithDic:para];
        self.navigationItem.backBarButtonItem = [LGUtil getBackButton];
        [self.navigationController pushViewController:_shangJiaViewController animated:YES];
    }else if(tableView.tag == step1T){//筛选第一个列表
        _s1data = [_sortcode objectAtIndex:indexPath.row];
        [_shaixuan.step1 setTitle:[_sort objectAtIndex:indexPath.row] forState:UIControlStateNormal];
        [_shaixuan.step2TB reloadData];//重载第二个列表
        [_shaixuan.step2 setTitle:@"全部" forState:UIControlStateNormal];
        [self reloadMainTableViewByA:_s1data B:_s2data C:_s3data];
        [_shaixuan hiddenAllTB];
    }else if (tableView.tag == step2T){//筛选第二个列表
        if ([_s1data isEqualToString:@"cat001"]) {//第一个选中的是餐饮
            _s2data = [_canyincode objectAtIndex:indexPath.row];
            [_shaixuan.step2 setTitle:[_canyin objectAtIndex:indexPath.row] forState:UIControlStateNormal];
            [self reloadMainTableViewByA:_s1data B:[_canyincode objectAtIndex:indexPath.row] C:_s3data];
        }else{//第一个选中的是娱乐
            _s2data = [_yulecode objectAtIndex:indexPath.row];
            [_shaixuan.step2 setTitle:[_yule objectAtIndex:indexPath.row] forState:UIControlStateNormal];
            [self reloadMainTableViewByA:_s1data B:[_yulecode objectAtIndex:indexPath.row] C:_s3data];
        }
    }else if (tableView.tag == step3T){
        _s3data = [_fangshicode objectAtIndex:indexPath.row];
        [_shaixuan.step3 setTitle:[_fangshi objectAtIndex:indexPath.row] forState:UIControlStateNormal];
        [self reloadMainTableViewByA:_s1data B:_s2data C:[_fangshicode objectAtIndex:indexPath.row]];
        
    }
    
}
-(void)reloadMainTableViewByA:(NSString *)placeType B:(NSString *)lableUuid C:(NSString *)orderBy
{
    UserInfo *info = [DataCenter getSingleton].userInfo;
    
    NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:
                          info.uuid,@"userUuid",
                          placeType,@"placeType",
                          lableUuid,@"lableUuid",
                          _lonLabel,@"longitude",
                          _latLabel,@"latitude",
                          orderBy,@"orderBy",
                          nil];
    
    [[RequestManager getSingleton] sendRequest:findPlaceByMap para:para callBack:^(id responseObj) {
        if ([[responseObj objectForKey:@"status"] intValue] == 2) {
            [_totalData removeAllObjects];
            [_scView.scTabV reloadData];
        }else{
            [_totalData removeAllObjects];
            _listData =[responseObj objectForKey:@"data"];
            [_totalData addObjectsFromArray:_listData];
            [_scView.scTabV reloadData];
        }
    }];
    [_shaixuan hiddenAllTB];
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView.tag == mainT) {//收藏列表
        return 103;
    }else if(tableView.tag == step1T){//筛选第一个列表
        return 30;
    }else if (tableView.tag == step2T){//筛选第二个列表
        return 30;
    }else if (tableView.tag == step3T){
        return 30;
    }else{
        return 30;
    }
    
}


/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_scView.scTabV addHeaderWithTarget:self action:@selector(headerRereshing)];
    // [_contentView.myTableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_scView.scTabV addFooterWithTarget:self action:@selector(footerRereshing)];
    
    // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
    _scView.scTabV.headerPullToRefreshText = @"下拉更新收藏列表";
    _scView.scTabV.headerReleaseToRefreshText = @"快松手~~";
    _scView.scTabV.headerRefreshingText = @"看看我收藏了哪些";
    
    _scView.scTabV.footerPullToRefreshText = @"下拉加载收藏列表";
    _scView.scTabV.footerReleaseToRefreshText = @"快松手~~";
    _scView.scTabV.footerRefreshingText = @"看看我收藏了哪些";
    
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _pageNum = 1;
        [self startRequest:[NSString stringWithFormat:@"%d",_pageNum] Flag:0];
    });
    [self resetShaiXuan];
}

- (void)footerRereshing
{
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        _pageNum = _pageNum+1;//加载下一页
        [self startRequest:[NSString stringWithFormat:@"%d",_pageNum] Flag:1];
    });
}
/*
 * 开始请求Web Service//这里我传的是一个写死的用户UUID做测试
 */
-(void)startRequest:(NSString *)page Flag:(int)flag;//头请求还是尾请求
{
    UserInfo *info = [DataCenter getSingleton].userInfo;
    if (info == nil ) {
        [_scView.scTabV headerEndRefreshing];
        [_scView.scTabV footerEndRefreshing];
        [[[[UIApplication sharedApplication] delegate] window] makeToast:@"登陆才能查看收藏哦~"
                                                                duration:1.0
                                                                position:@"center"];
        return;
    }
    NSDictionary *para = [NSDictionary dictionaryWithObjectsAndKeys:
                          info.uuid,@"appUserUuid",
                          page,@"page",
                          nil];
    [[RequestManager getSingleton] sendRequest:findCollectionByUser para:para callBack:^(id responseObj) {
        
        [self loadData:responseObj FLag:flag];
        
    }];
    [_scView.scTabV headerEndRefreshing];
    [_scView.scTabV footerEndRefreshing];
}
-(void)loadData:(NSDictionary*)res FLag:(int)flag
{
    if (flag == 0) {//头部刷新
        [_totalData removeAllObjects];
        _listData =[res objectForKey:@"data"];
        [_totalData addObjectsFromArray:_listData];
        [_scView.scTabV reloadData];
    }else{
        if (_listData.count == 0) {
            _pageNum = _pageNum-1;
        }else{
            _listData =[res objectForKey:@"data"];
            [_totalData addObjectsFromArray:_listData];
            [_scView.scTabV reloadData];
        }
    }
}
-(void)stepArrayData
{
    //一个是显示的数据，一个是对应给服务器发的编码。比如选择餐饮，往服务器发就是：cat001
    _sort = [[NSArray alloc]initWithObjects:@"餐饮",@"娱乐",nil];
    _sortcode = [[NSArray alloc]initWithObjects:@"cat001",@"cat002", nil];
    
    _canyin = [[NSArray alloc]initWithObjects:@"全部",@"中餐",@"西餐",@"日本料理",@"韩国料理",@"甜点", @"其他",nil];
    _canyincode = [[NSArray alloc]initWithObjects:
                   @"",
                   @"c65dadd6-7123-11e3-bcb4-3865526e31a9",
                   @"c6622ed7-7123-11e3-bcb4-3865526e31a9",
                   @"c6668969-7123-11e3-bcb4-3865526e31a9",
                   @"c670035e-7123-11e3-bcb4-3865526e31b1",
                   @"c670035e-7123-11e3-bcb4-3865526e31b2",
                   @"c66b4b15-7123-11e3-bcb4-3865526e31a9",nil];
    _yule = [[NSArray alloc]initWithObjects:@"全部", @"咖啡厅", @"酒吧", @"KTV", @"电影院", @"文化艺术", @"公园", @"市区景点", @"郊区景点",
             @"游乐游艺", @"温泉", @"运动", @"购物", nil];
    _yulecode = [[NSArray alloc]initWithObjects:
                 @"",
                 @"7b7ac207-7123-11e3-bcb4-3865526e31a9",
                 @"7f7c4347-7123-11e3-bcb4-3865526e31a9",
                 @"85c29eb1-7123-11e3-bcb4-3865526e31a9",
                 @"8767c38d-7123-11e3-bcb4-3865526e31a9",
                 @"89cb26c6-7123-11e3-bcb4-3865526e31a9",
                 @"a051bc32-7123-11e3-bcb4-3865526e31a9",
                 @"a1d7378c-7123-11e3-bcb4-3865526e31a9",
                 @"b6ac6648-7123-11e3-bcb4-3865526e31a9",
                 @"b6b3e288-7123-11e3-bcb4-3865526e31a9",
                 @"b6bcaac9-7123-11e3-bcb4-3865526e31a9",
                 @"b6c16b90-7123-11e3-bcb4-3865526e31a9",
                 @"c670035e-7123-11e3-bcb4-3865526e31a9", nil];
    _fangshi = [[NSArray alloc]initWithObjects:@"默认排序", @"最热收藏", @"价格最高", @"价格最低", @"离我最近", nil];
    _fangshicode = [[NSArray alloc]initWithObjects:@"listOrder",@"collectCount", @"payRankHigh", @"payRankLow",@"distance", nil];
    
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MobClick endLogPageView:@"收藏"];
}

@end
